package com.sams.interceptor;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.sams.entity.User;

public class LoginValidateInterceptor implements HandlerInterceptor{

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//登陆    所有请求 都需要 登陆后均可操作  
		
		// 验证是否登录 
		User user = (User)request.getSession().getAttribute("user");
 		if(user==null) {
			//response.sendRedirect(request.getContextPath()+"/login.html");
 			 
 			request.getRequestDispatcher("/login.html").forward(request, response);
			 return false;
		}else {
			//admin_index.html
			//如果是管理员 不拦截任何 请求
			if(user.getRoleid()==4) {
				return true;
			}
			
			//验证是否有权限  
			HashMap<String, String> authMap =(HashMap<String, String>)request.getSession().getAttribute("userAuthMap");
			System.out.println("request uri --->"+	request.getRequestURI());
			String uri=request.getRequestURI();
			if(uri.contains("sams/admin_index.jsp")) {
				return true;
			}
		 
			if(authMap.containsKey(uri) ) {
				
				return true;
			}else {
				request.setAttribute("error", "您没有权限访问此操作！请联系管理员");
				request.getRequestDispatcher("/error.jsp").forward(request, response);
				return false;
			}
		}
	 
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		// 如果登录成功了，从 session中 获取用户信息，并判断用户角色  
		//根据角色查询 用户 能操作的权限清单  放入Map中 （key ： 请求url   value ： 权限名称）
		// 
		
		
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
